//
//  BaseCommand.m
//  AFNetworking
//
//  Created by Henry on 2023/2/20.
//

#import "BaseCommand.h"
#import "SiterAPI.h"
#import <AWSIoT/AWSIoTDataManager.h>
#import <AWSIoT/AWSIoTMessage.h>
#import "ToolBox.h"
#import "TimeHelper.h"
#import "NVLogManager.h"

@interface BaseCommand()


@property(nonatomic,strong) Error_handler handler;

@end
@implementation BaseCommand

-(id)initWithDevId:(NSString *)thingName withThingTypeName:(NSString *)thingTypeName{
    if(self = [super init]){
        self.thingName = thingName;
        self.thingTypeName = thingTypeName;
    }
    return self;
}


-(id)getTopic{
    return nil;
}

-(id)getCommandContent{
    return nil;
}

-(id)getSubcribeTopic{
    return nil;
}

-(void)startSend:(void(^)(NSError *,id))handler{
    self.handler = handler;
    
    NSObject *senddata = [self getCommandContent];

    
    
    DebugInfo *info = [[DebugInfo alloc] init];
    [info setTime:[TimeHelper getCurrentTimes]];
    [info setIsSend:YES];
    [info setContent:senddata==nil?@"":([senddata isKindOfClass:[NSDictionary class]]?[self convertToJsonData:(NSDictionary *)senddata]:(NSString *)senddata)];
    [[ToolBox sharedToolBox] addDebugLog:info];
    if(self.handler!=nil){
    [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] subscribeToTopic:[self getSubcribeTopic] QoS:AWSIoTMQTTQoSMessageDeliveryAttemptedAtLeastOnce fullCallback:^(NSString * _Nonnull topic, AWSIoTMessage * _Nonnull message) {
             NVLogInfo(@"MQTT应答:%@",message.message);
             dispatch_sync(dispatch_get_main_queue(), ^{
                 DebugInfo *debuginfo = [[DebugInfo alloc] init];
                 [debuginfo setTime:[TimeHelper getCurrentTimes]];
                 [debuginfo setContent:message.message];
                 [[ToolBox sharedToolBox] addDebugLog:debuginfo];
                 NSData * data = [message.message dataUsingEncoding:NSUTF8StringEncoding];
                 NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                 if(jsonDict!=nil){
                     //刷新UI的代码放到主线程执行
                     NSNumber *code = jsonDict[@"code"];
                     if(code!=nil){
                         NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:[code intValue] userInfo:nil];
                         self.handler(error, nil);
                     }else{
                         self.handler(nil, jsonDict);
                     }

                 }else{
                     NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:500 userInfo:nil];
                     self.handler(error, nil);
                 }
                 [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[self getSubcribeTopic]];
             });
         }];
    }

        NVLogInfo(@"发送数据MQTT成功:%@", senddata);
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] publishString:senddata==nil?@"":([senddata isKindOfClass:[NSDictionary class]]?[self convertToJsonData:(NSDictionary *)senddata]:(NSString *)senddata) onTopic:[self getTopic] QoS:AWSIoTMQTTQoSMessageDeliveryAttemptedAtLeastOnce];


}



-(NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        NVLogInfo(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}


@end
